package com.study.tomcat.nio.http;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.*;

import java.io.OutputStream;
import java.nio.charset.StandardCharsets;

/**
 * @Author: huang
 * @Description 基于netty的响应
 * @Date: 2021-01-16 12:45
 */
public class MyNioResponse {

    private ChannelHandlerContext ctx;
    private HttpRequest req;

    public MyNioResponse(ChannelHandlerContext ctx, HttpRequest req) {
        this.ctx = ctx;
        this.req = req;
    }

    public void write(String s) throws Exception{
        if(null==s||0==s.length()){
            return;
        }

        try {
            FullHttpResponse response = new DefaultFullHttpResponse(
                    HttpVersion.HTTP_1_1,
                    HttpResponseStatus.OK,
                    Unpooled.wrappedBuffer(s.getBytes(StandardCharsets.UTF_8))
            );

            response.headers().set("Content-Type","text/html");
            ctx.write(response);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            ctx.flush();
            ctx.close();
        }
    }
}
